package org.changs.nav.ui.nav;

import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureSupportMapFragment;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;

import org.changs.aplug.plug.InjectEventBusOnResume;
import org.changs.nav.R;
import org.changs.nav.databinding.PoiMapFragmentBinding;
import org.changs.nav.event.PoiItemClickEvent;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import aplug.di.PoiOverlay;
import timber.log.Timber;

/**
 * Created by yincs on 2017/8/29.
 */

public class MapPoiListFragment extends BaseMapFragment implements InjectEventBusOnResume {
    private static final String TAG_POI_LIST = "TAG_POI_LIST";
    private static final String TAG_POI_SELECT = "TAG_POI_SELECT";

    public static MapPoiListFragment newInstance(ArrayList<PoiItem> poiItems) {
        Bundle args = new Bundle();
        args.putParcelableArrayList(TAG_POI_LIST, poiItems);
        MapPoiListFragment fragment = new MapPoiListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private PoiMapFragmentBinding mBinding;
    private AMap mAMap;
    private Marker mCenterMarker;
    private PoiOverlay mPoiOverlay;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.poi_map_fragment, container, false);
        initMap();
        initUI();
        initData(savedInstanceState);
        return mBinding.getRoot();
    }

    private void initData(Bundle savedInstanceState) {
        ArrayList<PoiItem> poiItems;
        int select;
        if (savedInstanceState == null) {
            poiItems = getArguments().getParcelableArrayList(TAG_POI_LIST);
            select = getArguments().getInt(TAG_POI_SELECT, 0);
        } else {
            poiItems = savedInstanceState.getParcelableArrayList(TAG_POI_LIST);
            select = savedInstanceState.getInt(TAG_POI_SELECT, 0);
        }
        showPoiList(poiItems, select);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(TAG_POI_LIST, mPoiOverlay.getPoiItems());
        outState.putInt(TAG_POI_SELECT, mPoiOverlay.getSelectIndex());
    }

    private void initMap() {
        if (mAMap == null) {
            mAMap = ((TextureSupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
        }
        mAMap.setTrafficEnabled(true);
        mAMap.showBuildings(true);
        mAMap.showMapText(true);
        mAMap.showIndoorMap(true);
//        mAMap.setMapType(AMap.MAP_TYPE_NIGHT);//夜景地图模式
        mAMap.setMapType(AMap.MAP_TYPE_NAVI);//导航地图模式

        UiSettings uiSettings = mAMap.getUiSettings();
        uiSettings.setCompassEnabled(false);
        uiSettings.setScaleControlsEnabled(false);
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setRotateGesturesEnabled(false);
        uiSettings.setZoomControlsEnabled(false);

        mAMap.setMyLocationEnabled(true);
        MyLocationStyle mLocationStyle = mAMap.getMyLocationStyle();
        mLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        // 自定义精度范围的圆形边框颜色
        mLocationStyle.strokeColor(Color.TRANSPARENT);
        //自定义精度范围的圆形边框宽度
        mLocationStyle.strokeWidth(0);
        // 设置圆形的填充颜色
        mLocationStyle.radiusFillColor(Color.TRANSPARENT);
        mAMap.setMyLocationStyle(mLocationStyle);
        mAMap.animateCamera(CameraUpdateFactory.zoomTo(15));


        mAMap.setOnMapLoadedListener(() -> mAMap.setPointToCenter(mBinding.getRoot().getMeasuredWidth() / 4 * 3,
                mBinding.getRoot().getMeasuredHeight() / 2));

        mAMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            int lastX, lastY;
            int touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();

            @Override
            public void onTouch(MotionEvent motionEvent) {
                int x = (int) motionEvent.getX();
                int y = (int) motionEvent.getY();
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    lastX = x;
                    lastY = y;
                } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    if (touchSlop < Math.sqrt(x * x + y * y)) {
                        Timber.d("onTouch: 有距离了");

                        mBinding.vCenter.setVisibility(View.VISIBLE);
                        removeCenterMarker();
                    }
                }
            }
        });
        mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (mBinding.vCenter.getVisibility() == View.VISIBLE) {
                    removeCenterMarker();
                    mCenterMarker = mAMap.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_click_map_center))
                            .position(cameraPosition.target));
                    mBinding.vCenter.setVisibility(View.GONE);
                }
            }
        });

        mAMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.equals(mCenterMarker)) {
                    Timber.d("onMarkerClick() called with: " + "marker = [" + marker + "]");
//                    getContext().addUniqueFragmentU(MainPoiDetailFragment.newInstance(marker.getPosition()), true);
                }
                return false;
            }
        });
    }

    private void initUI() {
        mBinding.vCenter.setVisibility(View.GONE);

        mBinding.btnZoomIn.setOnClickListener(v ->
                mAMap.animateCamera(CameraUpdateFactory.zoomOut()));
        mBinding.btnZoomOut.setOnClickListener(v ->
                mAMap.animateCamera(CameraUpdateFactory.zoomIn()));
    }

    private void removeCenterMarker() {
        if (mCenterMarker != null) {
            mCenterMarker.remove();
            mCenterMarker = null;
        }
    }

    public void showPoiList(ArrayList<PoiItem> poiItems, int select) {
        removeCenterMarker();
        if (mPoiOverlay != null) mPoiOverlay.removeFromMap();
        mPoiOverlay = new PoiOverlay(mAMap, poiItems);
        mPoiOverlay.addToMap();
        selectPoiItem(select);
    }

    public void selectPoiItem(int position) {
        mPoiOverlay.select(position);
        mPoiOverlay.zoomToSelect();
    }

    @Subscribe
    public void onEvent(PoiItemClickEvent event) {
        if (mPoiOverlay == null) {
            Timber.e("error onEvent: PoiOverlay == null");
            return;
        }
        selectPoiItem(event.index);
    }
}
